#include "tools.h"
#include <cmath>

// ---------------------------
void tools::DataBuffer::init(FILE* f)
// ---------------------------
{
	file = f;
	fread(buffer, 1, 10240, file);
	position = 0;
}

// --------------------------------------------
void tools::DataBuffer::getData(char* out, uint16_t l, bool string)
// --------------------------------------------
{
	for (uint16_t i=0; i<l; ++i)
	{
		if (position >= 10240)
		{
			fread(buffer, 1, 10240, file);
			position = 0;
		}
		if (string)
		{
			if (buffer[position] == 0)
			{
				out[i] = 0;
				++position;
				break;
			}
		}
		out[i] = buffer[position];
		++position;
	}
}

// ----------------------------------------------------
void tools::splitPath(std::list<std::string>* parts, std::string path)
// ----------------------------------------------------
{
	int slash;
	while ( slash = path.find('/', 1) )
	{
		if (slash == std::string::npos) break;
		parts->push_back(path.substr(1, slash-1));
		path = path.substr(slash);
	}
}

// ------------------------------------------------------------
bool tools::format_stagfs(FILE* fs, uint16_t nodesize, uint64_t nodes)
// ------------------------------------------------------------
{
	printf("Formatting... ");
	fseek(fs, 0, SEEK_SET);
	char buffer[nodesize];
	buffer[0] = 'T';
	buffer[1] = 'g';
	buffer[2] = 'F';
	buffer[3] = 'S';
	buffer[4] = ((char *)(&nodesize))[0];
	buffer[5] = ((char *)(&nodesize))[1];

	size_t written = 0;
	written = fwrite(buffer, 1, 6, fs);

	if (written != 6)
	{
		printf("error: wrote not as much as requested\n");
		return false;
	}

	for (uint16_t i=0; i<nodesize; ++i)
	{
		buffer[i] = 0;
	}

	written = 0;
	for (uint64_t i=0; i<nodes; ++i)
	{
		written += fwrite(buffer, 1, nodesize, fs);	
	}

	if (written != (nodes*nodesize))
	{
		printf("error: wrote not as much as requested\n");
		return false;
	}

	printf("done\n");
	return true;
}

// ----------------------------------------------
void tools::copyChars(const char* in, char* out, uint16_t len)
// ----------------------------------------------
{
	for (uint16_t i=0; i<len; ++i)
	{
		out[i] = in[i];
	}
}

